﻿using log4net;
using Mangox.Common;
using Mangox.Common.Tookit;
using Mangox.Model.MyBusinessDB;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Mangox.BLL.Stock
{
    public class UWPDeviceBLL
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";

        public List<UWP_Device> GetUWP_DeviceList()
        {
            List<UWP_Device> list = null;
            using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
            {
                list = dbContext.UWP_Device.ToList();
            }
            return list;
        }

        /// <summary>
        /// 根据主键获取
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public UWP_Device GetUWP_Device(int ID)
        {
            UWP_Device dev = null;
            try
            {
                using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
                {
                    //这种写法deviceID必须是主键
                    dev = dbContext.UWP_Device.Find(ID);
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "GetUWP_Device.ID fail-{0}", ex);
            }
            return dev;
        }

        /// <summary>
        /// 根据deviceID获取
        /// </summary>
        /// <param name="deviceID"></param>
        /// <returns></returns>
        public UWP_Device GetUWP_Device(string deviceID)
        {
            UWP_Device dev = null;
            try
            {
                using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
                {
                    var devList = (dbContext.UWP_Device.Where(u => u.DeviceID == deviceID).ToList()) as List<UWP_Device>;

                    if (devList.Count > 0)
                    {
                        dev = devList[0];
                    }
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "GetUWP_Device.deviceID fail-{0}", ex);
            }
            return dev;
        }

        /// <summary>
        /// 添加设备用户，先检查此用户是否存在，存在则增加count
        /// 如果是新用户记录到设备表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool AddUWP_Device(UWP_Device param)
        {
            
            try
            {
                var dev = GetUWP_Device(param.DeviceID);
                if (dev == null)
                {
                    //var json = "{\"ID\":0,\"DeviceID\":\"93a669ee-a5f3-a6e0-6270-b076c68a4292\",\"State\":null,\"CreateTime\":null,\"Openid\":null,\"FriendlyName\":\"LAPTOP-5OBHI7RG\",\"OperatingSystem\":\"WINDOWS\",\"SystemFirmwareVersion\":\"\",\"SystemHardwareVersion\":\"\",\"SystemManufacturer\":\"LENOVO\",\"SystemProductName\":\"80WF\",\"SystemSku\":\"LENOVO_MT_80WF_BU_idea_FM_Lenovo XiaoXin Air 13IKB Pro\",\"UseCount\":null,\"Remark\":null,\"LastUseTime\":null,\"DeviceFamily\":\"Windows.Desktop\",\"DeviceFamilyVersion\":\"10.0.17134.590\"}";
                    //model = JsonCommon.JsonToMode<UWP_Device>(json);

                    log.InfoFormat("添加UWP_Device信息{0}", JsonCommon.ToJson(param));
                                       
                    using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
                    {
                        param.UseCount = 1;
                        param.State = 1;
                        param.CreateTime = DateTime.Now;
                        param.LastUseTime = DateTime.Now;
                        dbContext.UWP_Device.Add(param);
                        return dbContext.SaveChanges() > 0;
                    }
                }
                else
                {
                    //设备存在，只更新UseCount；如果信息不全则补全
                    var temp = new UWP_Device();
                    if (string.IsNullOrEmpty(dev.FriendlyName) || string.IsNullOrEmpty(dev.DeviceFamilyVersion))
                    {
                        //兼容旧APP(1.33)
                        ObjectReflection.AutoMapping(param, temp);
                    }
                    temp.ID = dev.ID;
                    temp.UseCount = ++dev.UseCount;
                    temp.LastUseTime = DateTime.Now;
                    temp.DeviceFamilyVersion = dev.DeviceFamilyVersion;
                    UpdateUWP_Device(temp);
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "AddUWPDevice fail-{0}", ex);
            }
            
            return false;
        }


        public UWP_Device UpdateUWP_Device(UWP_Device param)
        {
            UWP_Device model = null;
            try
            {
                using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
                {
                    //var list = dbContext.UWP_Device.Where(u => u.DeviceID == model.DeviceID).ToList() as List<UWP_Device>;
                    //if (list.Count <= 0)
                    //{
                    //    return null;
                    //}
                    //dev = list[0];

                    model = dbContext.UWP_Device.Find(param.ID);

                    ObjectReflection.AutoMapping(param, model);

                    if (dbContext.SaveChanges() > 0)
                    {
                        log.InfoFormat(className + "UpdateUWP_Device 更新设备成功 model-{0}", JsonCommon.ToJson(model));
                        return model;
                    }
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "UpdateUWP_Device fail-{0}", ex);
            }
            return model;
        }


        /// <summary>
        /// 添加用户活跃，uwp、小程序
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool AddUserActive(UserActive param)
        {
            try
            {
                if (param == null)
                {
                    return false;
                }
                log.InfoFormat(className + "Add UserActive");
                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    //var temp = new UserActive()
                    //{
                    //    Source = model.Source,
                    //    IsFirst = model.IsFirst,
                    //    DevId = model.DevId,
                    //    CreateTime = DateTime.Now,
                    //    State = 1,
                    //    Versions = model.Versions,
                    //    Openid = model.Openid
                    //};

                    param.State = 1;
                    param.CreateTime = DateTime.Now;

                    db.UserActives.Add(param);
                    return db.SaveChanges() > 0;
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "AddUserActive fail-{0}", ex);
            }
            return false;
        }

        /// <summary>
        /// 用户活跃，统计使用量
        /// </summary>
        /// <param name="SatrtDate"></param>
        /// <param name="EndDate"></param>
        /// <returns></returns>
        public int GetUserActiveCount(string SatrtDate = null, string EndDate = null)
        {
            try
            {
                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    //var result = db.UserActives.Where(a => a.CreateTime );
                    return db.UserActives.Count();
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "GetNewsByID fail-{0}", ex);
            }
            return 0;
        }

        #region 记录用户页面使用习惯

        /// <summary>
        /// 添加用户使用页面情况
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool AddUserActivePage(UserActivePage param)
        {
            try
            {
                if (param == null)
                {
                    return false;
                }
                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    param.CreateTime = DateTime.Now;

                    db.UserActivePages.Add(param);
                    var f = db.SaveChanges() > 0;
                    return f;
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "AddUserActivePage fail-{0}", ex);
            }
            return false;
        }

        #endregion



    }
}
